<template>
  <div class="app-container">
    <el-form ref="helpForm" :model="helpForm" :rules="rules" label-width="100px" class="demo-ruleForm">
      <el-row :gutter="10">
        <el-col :span="18" :offset="3">
          <el-col :span="12">
            <el-form-item label="标题" prop="title">
              <el-input v-model.trim="helpForm.title" placeholder="请填写标题" :disabled="isFormDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="msgCategory" label="消息类型">
              <el-select v-model="helpForm.msgCategory" placeholder="消息类型选择" :disabled="isFormDisabled">
                <el-option v-for="item in msgCategoryOption" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker v-model="helpForm.startTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker v-model="helpForm.endTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="helpForm.priority" placeholder="优先级选择" :disabled="isFormDisabled">
                <el-option v-for="item in priorityOption" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="通告对象" prop="msgType">
              <el-select v-model="helpForm.msgType" placeholder="通告对象选择" :disabled="isFormDisabled" @change="msgTypeChange">
                <el-option v-for="item in msgTypeOption" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="showUserList" :span="12">
            <el-form-item label="指定用户">
              <el-select
                v-model="userNames"
                multiple
                filterable
                allow-create
                default-first-option
                remote
                reserve-keyword
                placeholder="请输入关键词"
                :remote-method="remoteMethod"
:loading="loading"
                clearable
                @change="handleSelectBranchCom"
              >
                <el-option v-for="item in dddd" :key="item.value" :label="item.label" style="height: 30px" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <div class="uedit-warp">
              <div class="goods-editor">
                <div v-if="isFormDisabled" class="popDisabled" />
                <!-- 工具栏容器 -->
                <div id="toolbar-container" />
                <!-- 编辑器容器 -->
                <div id="editor">
                  <!-- <p>This is the initial editor content.</p> -->
                </div>
              </div>
            </div>
          </el-col>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" style="text-align: center">
      <el-button v-show="clickType == '新增'" type="success" plain @click="saveAndPublishAnnots('helpForm')">保存并发布</el-button>
      <el-button type="primary" plain @click="confirmBtn('helpForm')">{{ $t('btn.confirm') }}</el-button>
      <el-button type="danger" plain @click="cancel()">{{ $t('btn.close') }}</el-button>
    </div>
  </div>
</template>

<script>
import '@ckeditor/ckeditor5-build-decoupled-document/build/translations/zh-cn'
import { annotAdd, annotEdit, saveAndPublishAnnot } from '@/api/announcement'
import { uploadImg } from '@/api/system-set'
import { getUserList } from '@/api/authority'
import i18n from '@/lang'
export default {
  components: {},
  props: {
    helpForm: {
      type: Object,
      default: function() {
        return {
          title: '', // 分类
          msgCategory: '', // 标题
          startTime: null, // 排序
          endTime: '', // 启用状态
          priority: '',
          msgType: '',
          userNames: [],
        }
      },
    },
    clickType: {
      type: String,
      default: function() {
        return ''
      },
    },
    classificationList: {
      type: Array,
      default: function() {
        return []
      },
    },
  },
  data() {
    return {
      // 优先级
      priorityOption: [
        {
          label: '高',
          value: 'H',
        },
        {
          label: '中',
          value: 'M',
        },
        {
          label: '低',
          value: 'L',
        },
      ],
      // 消息类型
      msgCategoryOption: [
        {
          label: '通知公告',
          value: '1',
        },
        {
          label: '系统消息',
          value: '2',
        },
      ],
      // 用户类型
      msgTypeOption: [
        {
          label: '指定用户',
          value: 'USER',
        },
        {
          label: '全体用户',
          value: 'ALL',
        },
      ],
      // 发布状态
      sendStatusOption: [
        {
          label: '未发布',
          value: 0,
        },
        {
          label: '已发布',
          value: 1,
        },
        {
          label: '已撤销',
          value: 2,
        },
      ],
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        msgCategory: [{ required: true, message: '请选择消息类型', trigger: 'change' }],
        startTime: [{ required: true, message: '请选择开始时间', trigger: 'blur' }],
        endTime: [{ required: true, message: '请选择结束时间', trigger: 'blur' }],
        priority: [{ required: true, message: '请选择优先等级', trigger: 'change' }],
        msgType: [{ required: true, message: '请选择通告类型', trigger: 'change' }],
      },
      id: null,
      editor: null,
      // 模糊搜索 用户名
      loading: false,
      states: [],
      list: [],
      dddd: [],
      searchid: [],
      userNames: [],
      showUserList: false,
    }
  },
  computed: {
    isFormDisabled() {
      return false
    },
  },
  watch: {
    'helpForm.sort': function(val) {
      this.helpForm.sort = val != null ? Number(val) : null
    },
  },
  mounted() {
    const that = this
    this.initCKEditor()
    if (this.helpForm.userNames != undefined) {
      var editUserNames = this.helpForm.userNames.split(',')
      this.userNames = editUserNames
      if (this.helpForm.msgType == 'USER') {
        this.showUserList = true
      } else {
        this.showUserList = false
      }
      setTimeout(function() {
        if (that.clickType == '编辑') {
          // 编辑
          that.editor.setData(that.helpForm.msgContent)
        }
      }, 100)
    }
  },
  methods: {
    handleSelectBranchCom($event, item) {
      // 如果要获取选择的 id或者名字   从item中取值
      this.searchid = item
      console.log($event)
    },
    // 搜索模糊查询数据下拉框
    async remoteMethod(query) {
      var that = this
      const params = {
        username: query,
        order: 'DESC',
        pageNumber: 1,
        pageSize: 10,
      }
      const res = await getUserList(params)
      if (res.code != '200') return
      that.states = res.data.records
      that.list = that.states.map((item) => {
        return { value: item.username, label: item.username }
      })

      setTimeout(() => {
        if (query !== '') {
          that.loading = true
          setTimeout(() => {
            that.loading = false
            that.dddd = that.list.filter((item) => {
              // 这里的label值对应着 上面遍历 return  返回的label:item.name
              return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1
            })
          }, 200)
        } else {
          that.dddd = []
        }
      }, 100)
    },

    initCKEditor() {
      class UploadAdapter {
        constructor(loader) {
          this.loader = loader
        }
        async upload() {
          // 重置上传路径
          const data = new FormData()
          data.append('file', await this.loader.file)
          return new Promise((resolve, reject) => {
            uploadImg(data)
              .then((res) => {
                if (res.code == '200') {
                  resolve({
                    default: res.data,
                  })
                }
              })
              .catch((err) => {
                reject(err)
              })
          })
        }
      }
      window.DecoupledEditor.create(document.querySelector('#editor'), {
        language: i18n.locale == 'zh' ? 'zh-cn' : 'en-us',
        ckfinder: {
          uploaded: 1,
          url: '/',
        },
        link: {
          addTargetToExternalLinks: true,
        },
        mediaEmbed: {
          providers: [
            {
              name: 'myprovider',
              url: [/^lizzy.*\.com.*\/media\/(\w+)/, /^www\.lizzy.*/, /(http|https):\/\/([\w.]+\/?)\S*/],
              html: (match) => {
                // 获取媒体url
                const input = match['input']
                return '<div style="position: relative; padding-bottom: 100%; height: 0; padding-bottom: 70%;">' + `<iframe src="${input}" ` + 'style="position: absolute; width: 100%; height: 100%; top: 0; left: 0;" ' + 'frameborder="0" allowtransparency="true" allow="encrypted-media">' + '</iframe>' + '</div>'
              },
            },
          ],
        },
      }).then((editor) => {
        editor.plugins.get('FileRepository').createUploadAdapter = (loader) => {
          return new UploadAdapter(loader)
        }
        const toolbarContainer = document.querySelector('#toolbar-container')
        toolbarContainer.appendChild(editor.ui.view.toolbar.element)
        this.editor = editor // 将编辑器保存起来，用来随时获取编辑器中的内容等，执行一些操作
      })
    },
    cancel() {
      this.$parent.$parent.colseDialog('no')
    },
    // 清空内容
    clearEdit() {
      this.editor.setData('')
    },
    // 保存并发布
    async saveAndPublishAnnots(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          if (!this.editor.getData()) {
            this.$message.warning('请输入富文本框内容')
            return
          }
          const helpForm = this.helpForm
          helpForm.userNames = this.userNames.join(',')
          helpForm.msgContent = this.editor.getData()
          const res = await saveAndPublishAnnot(helpForm)
          if (res.code != '200') return
          this.$parent.$parent.colseDialog('yes')
          this.clearEdit()
        }
      })
    },
    // 发布
    msgTypeChange(val) {
      console.log(val)
      if (val == 'USER') {
        this.showUserList = true
      } else {
        this.showUserList = false
      }
    },
    // 保存
    confirmBtn(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          if (!this.editor.getData()) {
            this.$message.warning('请输入富文本框内容')
            return
          }
          const helpForm = this.helpForm
          helpForm.userNames = this.userNames.join(',')
          helpForm.msgContent = this.editor.getData()
          if (this.clickType == '新增') {
            // 新增
            const res = await annotAdd(helpForm)
            if (res.code != '200') return
            this.$parent.$parent.colseDialog('yes')
            this.clearEdit()
          } else {
            // 编辑
            const res = await annotEdit(helpForm)
            if (res.code != '200') return
            this.$parent.$parent.colseDialog('yes')
            this.clearEdit()
          }
        }
      })
    },
  },
}
</script>
<style scoped lang="scss">
.uedit-warp {
  margin: 20px 0;
  .goods-editor {
    position: relative;
    z-index: 1;
  }
  .popDisabled {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    z-index: 10;
    background-color: rgba(205, 205, 205, 0.3);
  }
}
.confirm-btn {
  width: 100%;
  text-align: center;
  margin-top: 40px;
}
.confirm-btn .btn {
  width: 200px;
}

#editor {
  min-height: 300px;
  max-height: 350px;
  overflow-y: auto;
  border: 1px solid #c4c4c4;
}
</style>
